<?php

/**
 * Created by PhpStorm.
 * User: liu85
 * Date: 2017/10/23
 * Time: 20:32
 */
namespace app\common\helper;

use app\common\cache\SmsCache;
use app\common\consts\BaseConst;
use app\common\utils\MyRedis;

class RequestHelper
{

    /**
     * 验证ip是否合法
     * @param $ip
     * @return boolean
     */
    public static function checkIp($ip){
        $arr=explode('.',$ip);
        if(count($arr) != 4){
            return false;
        }else{
            for($i = 0; $i < 4; $i++){
                if(($arr[$i] <'0') || ($arr[$i] > '255')){
                    return false;
                }
            }
        }
        return true;
    }


    /**
     * 获取客户端真实IP，不要使用 ThinkPHP 的 get_client_ip() 方法
     * @return array|false|string
     */
    public static function getClientIp() {
        if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        $onlineipmatches = explode(',', $onlineip);
        $onlineip = $onlineipmatches[0] ? $onlineipmatches[0] : '0.0.0.0';
        unset($onlineipmatches);
        return $onlineip;
    }

    /**
     * @return bool
     */
    public static function checkIpOverMaxRequest()
    {
        $ip = self::getClientIp();
        if (SmsCache::getIpDaySendCount($ip) > BaseConst::DAY_IP_MAX_SEND_COUNT) {
            return true;
        }
        return false;
    }

    /**
     * @param $mobile
     * @return bool
     */
    public static function checkMobileOverMaxRequest($mobile)
    {
        if (SmsCache::getMobileDaySendCount($mobile) > BaseConst::DAY_MOBILE_MAX_SEND_COUNT) {
            return true;
        }
        return false;
    }
}